package org.xhnews.parsers;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.xhnews.database.DatabaseManager;
import org.xhnews.log.RaspberryLogger;
import org.xhnews.to.City;
import org.xhnews.to.Province;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class CityPullXMLParser {
	public static boolean readCityToDB(InputStream inputStream,
			String inputEncoding) {
		try {
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance();
			XmlPullParser pullParser = pullParserFactory.newPullParser();
			Reader reader = new InputStreamReader(inputStream, inputEncoding);
			reader.read();
			pullParser.setInput(reader);
			int eventType = pullParser.getEventType();
			Province province = new Province();
			City city = new City();
			int type = -1;// -1:null,0:province,1:city
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String nodeName = pullParser.getName();
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					if ("ZoneTable".equals(nodeName)) {
						province = new Province();
						type = 0;
					} else if ("AreaTable".equals(nodeName)) {
						city = new City();
						type = 1;
					} else if ("ID".equals(nodeName)) {
						if (type == 0 && province != null) {
							province.setId(Integer.parseInt(pullParser
									.nextText()));
						} else if (type == 1 && city != null) {
							city.setId(Integer.parseInt(pullParser.nextText()));
						}
					} else if ("Zone".equals(nodeName)) {
						if (type == 0 && province != null) {
							province.setName(pullParser.nextText());
						}
					} else if ("ZoneID".equals(nodeName)) {
						if (type == 1 && city != null) {
							city.setProvinceID(Integer.parseInt(pullParser
									.nextText()));
						}
					} else if ("Area".equals(nodeName)) {
						if (type == 1 && city != null) {
							city.setName(pullParser.nextText());
						}
					} else if ("AreaCode".equals(nodeName)) {
						if (type == 1 && city != null) {
							city.setCode(Integer
									.parseInt(pullParser.nextText()));
						}
					}
					break;
				case XmlPullParser.END_TAG:
					if ("ZoneTable".equals(nodeName)) {
						if (!DatabaseManager.insertProvince(province)) {
							return false;
						}
						province = null;
						type = -1;
					} else if ("AreaTable".equals(nodeName)) {
						if (!DatabaseManager.insertCity(city)) {
							return false;
						}
						city = null;
						type = -1;
					}
					break;
				}
				eventType = pullParser.next();
			}// end while
			return true;
		} catch (Exception e) {
			RaspberryLogger.getInstance().info(e.getMessage());
			e.printStackTrace();
			return false;
		}
	}

}
